<?php

namespace app\api\controller\order;

use app\api\controller\AuthController;
use app\api\service\CartService;
use app\api\service\ExpressService;
use app\api\service\IntegralService;
use app\api\service\OrderService;
use app\api\service\PaymentService;
use app\api\service\UserGradeService;
use think\exception\ValidateException;
use think\facade\Db;

class OrderController extends AuthController
{

    /**
     * 获取自提点
     */
    public function getPickPointList()
    {
        $param = $this->request->param();
        $store_id = empty($param['store_id']) ? 1 : $param['store_id'];
        if (empty($param['lat']) || empty($param['lng'])) {
            return json(['code' => 0, 'data' => '', 'msg' => '获取位置失败!']);
        }
        $lat = $param['lat'];
        $lng = $param['lng'];
        $list = OrderService::findAllPickPoint($lat, $lng, $store_id);
        return json(['code' => 1, 'data' => $list, 'msg' => '请求成功!']);
    }

    /**
     * 物流信息
     */
    public function logisticsInfo()
    {
        $order_id = $this->request->param('order_id/d');
        $order = OrderService::findOrder($order_id);
        $courier_number = $order['courier_number']; ///9867463818845
        if ($courier_number) {
            $express = new ExpressService($courier_number);
            $rst = $express->Query();
        } else {
            $rst = [];
        }
        return json(['code' => 1, 'data' => $rst, 'msg' => '请求成功!']);
    }

    /**
     *
     * 获取订单列表
     * */
    public function index()
    {
        $param = $this->request->param();

        $user_id = $this->request->user['user_id'];
        $orders = OrderService::getOrderList($user_id, $param);

        return json(['code' => 1, 'data' => $orders, 'msg' => '请求成功!']);
    }

    /**
     *
     * 获取订单详情
     * */
    public function read()
    {
        $order_id = $this->request->param('order_id/d');

        $order = OrderService::findOrder($order_id);

        return json(['code' => 1, 'data' => $order, 'msg' => '请求成功!']);
    }

    /**
     * 购物车生成订单
     */
    public function cartSaveOrder()
    {
        $param = $this->request->param();
        $cids = empty($param['cids']) ? '' : $param['cids'];
        try {
            validate('CorderValidate')->check($param);
        } catch (ValidateException $e) {
            return json(['code' => 0, 'msg' => $e->getError()]);
        }

        $user_id = $this->request->user['user_id'];
        $logistics_mode = empty($param['logistics_mode']) ? 1 : 2;
        $param['logistics_mode'] = $logistics_mode; // 配送方式1、快递 2、自提

        if ($param['logistics_mode'] != 1) {
            if (empty($param['pick_point_id'])) {
                return json(['code' => 0, 'msg' => '请选择自提点']);
            }
            $is_pick_point = Db::name('pick_point')->where(['store_id' => $param['store_id'], 'status' => 1, 'id' => $param['pick_point_id'], 'delete_time' => 0])->find();
            if (empty($is_pick_point)) {
                return json(['code' => 0, 'msg' => '自提点不存在']);
            }
        }

        //判断购物车商品是否可以支付
        list($list, $total_amount, $c, $m, $user_trade_id, $total_give_interal) = CartService::cartTotal($param, $user_id, $cids);
        if ($c == 0) {
            return json(['code' => 0, 'msg' => $m]);
        }
        if (empty($list)) {
            return json(['code' => 0, 'msg' => '未找到指定的商品']);
        }

        //会员折扣
        list($total_amount, $grade_discount_amount) = UserGradeService::gradeDiscount($user_trade_id, $total_amount);

        //优惠劵等后面再修改
        $real_amount = $total_amount - 0;

        $o_d['give_integral'] = $total_give_interal; //总共赠送的积分

        $order_no = PaymentService::generateOrderNum();
        $out_trade_no = PaymentService::generateOrderNum(10);

        $data = array_merge($param, $o_d, [
            'user_id' => $user_id,
            'order_type' => 1,
            'discount_amount' => 0,
            'real_amount' => $real_amount,
            'order_no' => $order_no,
            'out_trade_no' => $out_trade_no,
            'grade_discount_amount' => $grade_discount_amount,
            'total_amount' => $total_amount,
        ]);

        $result = OrderService::saveCartOrder($data, $list);
        if ($result === false) {
            return json(['code' => 0, 'msg' => '下单失败!']);
        }

        $orderTrade = Db::name('order_trade')->where('trade_status', '<>', 1)->where('store_id', $data['store_id'])->where('out_trade_no', $out_trade_no)->find();
        if ($real_amount <= 0) {
            Db::name('order_trade')->where('id', $orderTrade['id'])->update(['trade_status' => 1]);
            if ($logistics_mode == 2) {
                Db::name('order')->where('id', $orderTrade['order_id'])->update(['status' => 3, 'ship_time' => time()]);
            } else {
                Db::name('order')->where('id', $orderTrade['order_id'])->update(['status' => 2]);
            }
            return json(['code' => 1, 'msg' => '支付成功!', 'data' => []]);
        } else {
            return json(['code' => 1, 'msg' => '下单成功，请及时支付!', 'oid' => $orderTrade['order_id']]);
        }
    }

    /**
     *
     * 生成订单
     * */
    public function save()
    {
        $param = $this->request->param();

        try {
            validate('OrderValidate')->check($param);
        } catch (ValidateException $e) {
            return json(['code' => 0, 'msg' => $e->getError()]);
        }

        $logistics_mode = empty($param['logistics_mode']) ? 1 : 2;
        $param['logistics_mode'] = $logistics_mode;
        if (!empty($param['goods_id'])) {
            $goods = OrderService::findSingleGoods($param['goods_id']);
            if ($goods['spec_type'] != 1 && empty($param['sku_id'])) {
                return json(['code' => 0, '非法请求']);
            }
        }

        if ($param['logistics_mode'] != 1) {
            if (empty($param['pick_point_id'])) {
                return json(['code' => 0, '请选择自提点']);
            }
            $is_pick_point = Db::name('pick_point')->where(['store_id' => $param['store_id'], 'status' => 1, 'id' => $param['pick_point_id'], 'delete_time' => 0])->find();
            if (empty($is_pick_point)) {
                return json(['code' => 0, '自提点不存在']);
            }
        }
        if (!empty($param['sku_id'])) {
            $goods = OrderService::findManyGoods($param['sku_id'], $param['goods_id']);
        }

        if (empty($goods)) {
            return json(['code' => 0, 'msg' => '商品已下架']);
        }

        $param['buy_num'] = isset($param['buy_num']) ? $param['buy_num'] : 1;

        if ($goods['stock'] < $param['buy_num']) {
            return json(['code' => 0, 'msg' => '库存不足']);
        }

        $user_id = $this->request->user['user_id'];

        $user_trade_id = OrderService::findUserGrade($user_id);

        if ($goods['is_limit_member'] == 1 && !empty($goods['restricted_members'])) {
            $in = explode('-', $goods['restricted_members']);
            if (!in_array($user_trade_id, $in)) {
                return json(['code' => 0, 'msg' => '对不起该商品为会员专享,您还未成为会员!']);
            }
        }

        if ($goods['is_subsidy'] == 1) {
            $goods['sell_price'] = $goods['subsidy_price'];
        }

        if ($goods['spec_type'] == 1) {
            $goods['image'] = $goods['main_image'];
        }

        if ($goods['spec_type'] == 2) {
            $goods['image'] = !empty($goods['image']) ? $goods['image'] : $goods['main_image'];
        }

        $total_amount = number_format($goods['sell_price'] * $param['buy_num'], 2);

        //会员折扣
        list($total_amount, $grade_discount_amount) = UserGradeService::gradeDiscount($user_trade_id, $total_amount);
        // print_r($grade_discount_amount);exit;

        $discount_amount = 0;
        if (!empty($param['coupon_id'])) {
            $discount_amount = OrderService::getCouponDiscountAmount($user_id, $param['coupon_id'], $goods['goods_id'], $total_amount);
        }
        $real_amount = $total_amount - $discount_amount;

        $integral_scale = IntegralService::getGiveIntegralScale($param['store_id']);
        if ($integral_scale > 0 && $goods['is_give_integral'] == 1) {
            $give_integral = floor($real_amount * ($integral_scale / 100));
            $bs = OrderService::giveBirthdayPoint($user_id); //判断是否生日
            if ($bs) {
                $give_integral = bcmul($give_integral, $bs);
            }
            $goods['give_integral'] = $give_integral;
        }

        $order_no = PaymentService::generateOrderNum();
        $out_trade_no = PaymentService::generateOrderNum(10);

        $data = array_merge($param, $goods, [
            'user_id' => $user_id,
            'order_type' => 1,
            'discount_amount' => $discount_amount,
            'real_amount' => $real_amount,
            'order_no' => $order_no,
            'out_trade_no' => $out_trade_no,
            'grade_discount_amount' => $grade_discount_amount,
            'total_amount' => $total_amount,
        ]);

        $result = OrderService::saveOrder($data, false, true);

        if ($result === false) {
            return json(['code' => 0, 'msg' => '下单失败!']);
        }

        $orderTrade = Db::name('order_trade')->where('trade_status', '<>', 1)->where('store_id', $data['store_id'])->where('out_trade_no', $out_trade_no)->find();
        if ($real_amount <= 0) {
            Db::name('order_trade')->where('id', $orderTrade['id'])->update(['trade_status' => 1]);
            if ($logistics_mode == 2) {
                Db::name('order')->where('id', $orderTrade['order_id'])->update(['status' => 3, 'ship_time' => time()]);
            } else {
                Db::name('order')->where('id', $orderTrade['order_id'])->update(['status' => 2]);
            }
            return json(['code' => 1, 'msg' => '支付成功!', 'data' => []]);
        } else {
            return json(['code' => 1, 'msg' => '下单成功，请及时支付!', 'oid' => $orderTrade['order_id']]);
        }
    }

    /**
     * 订单支付
     */
    public function orderPay()
    {
        $param = $this->request->param();
        $user_id = $this->request->user['user_id'];
        if (empty($param['store_id'])) {
            return json(['code' => 0, 'msg' => '非法参数!']);
        }

        if (empty($param['payment_type'])) {
            return json(['code' => 0, 'msg' => '请选择支付方式!']);
        }

        if (empty($param['oid'])) {
            return json(['code' => 0, 'msg' => '未找到指定订单!']);
        }
        $out_trade_no = PaymentService::generateOrderNum(10);
        $orderInfo = Db::name('order')->where('id', $param['oid'])->where('user_id', $user_id)->where('status', 1)
            ->find();
        Db::name('order_trade')->insert([
            'store_id' => $param['store_id'],
            'order_id' => $param['oid'],
            'trade_method' => $param['payment_type'],
            'out_trade_no' => $out_trade_no,
            'trade_fee' => $orderInfo['real_amount'],
            'trade_status' => -1,
        ]);

        $config = PaymentService::findPaymentConfig($param['store_id'], $param['payment_type']);
        if (empty($config)) {
            return json(['code' => 0, 'msg' => '支付异常!']);
        }

        if (!empty($orderInfo)) {
            $payment_data = [
                'config' => $config,
                'trade_method' => $param['payment_type'],
                'out_trade_no' => $out_trade_no,
                'real_amount' => $orderInfo['real_amount'],
            ];
            if ($param['payment_type'] == 1) {
                $payment_data['notify_url'] = 'https://xiangyule.jcyqkj.cn/api/order/trade/wx/notify';
            }

            if ($param['payment_type'] == 2) {
                $payment_data['notify_url'] = 'https://xiangyule.jcyqkj.cn/api/order/trade/ali/notify';
            }
            $prepay_info = PaymentService::createOrder($payment_data);
            if (!empty($prepay_info)) {
                return json([
                    'code' => 1,
                    'data' => [
                        'out_trade_no' => $out_trade_no,
                        'prepay_info' => $prepay_info,
                    ],
                    'msg' => '获取成功!',
                ]);
            }
        } else {
            return json(['code' => 0, 'msg' => '未找到指定订单!']);
        }
    }

    /**
     * 免费拿商品
     * */
    public function free()
    {
        $param = $this->request->param();

        try {
            validate('OrderValidate.free')->check($param);
        } catch (ValidateException $e) {
            return json(['code' => 0, 'msg' => $e->getError()]);
        }

        if (!empty($param['goods_id'])) {
            $goods = OrderService::findSingleGoods($param['goods_id']);
        }

        if (!empty($param['sku_id'])) {
            $goods = OrderService::findManyGoods($param['sku_id'], $param['goods_id']);
        }
        if (empty($goods)) {
            return json(['code' => 0, 'msg' => '商品已下架']);
        }

        $param['buy_num'] = 1;
        if ($goods['stock'] < $param['buy_num']) {
            return json(['code' => 0, 'msg' => '库存不足']);
        }

        if ($goods['is_free_task'] != 1) {
            return json(['code' => 0, 'msg' => '对不起该商品不能参与免费拿!']);
        }

        $user_id = $this->request->user['user_id'];

        $user_trade_id = OrderService::findUserGrade($user_id);

        if ($goods['is_limit_member'] == 1 && !empty($goods['restricted_members'])) {
            $in = explode('-', $goods['restricted_members']);
            if (!in_array($user_trade_id, $in)) {
                return json(['code' => 0, 'msg' => '对不起该商品为会员专享,您还未成为会员!']);
            }
        }

        if ($goods['spec_type'] == 1) {
            $goods['image'] = $goods['main_image'];
        }

        if ($goods['spec_type'] == 2) {
            $goods['image'] = !empty($goods['image']) ? $goods['image'] : $goods['main_image'];
        }

        $real_amount = number_format($goods['sell_price'] * $param['buy_num'], 2);
        $order_no = PaymentService::generateOrderNum();
        $out_trade_no = PaymentService::generateOrderNum(10);

        $data = array_merge($param, $goods, [
            'user_id' => $user_id,
            'order_type' => 4,
            'real_amount' => $real_amount,
            'order_no' => $order_no,
            'out_trade_no' => $out_trade_no,
        ]);

        $result = OrderService::saveOrder($data, true);

        return $result ? json(['code' => 1, 'msg' => '任务开启成功!']) : json(['code' => 0, 'msg' => '任务开启失败!']);
    }

    /**
     * 发起退款
     * */
    public function refund()
    {
        $param = $this->request->param();

        if (empty($param['order_id'])) {
            return json(['code' => 0, 'msg' => '非法参数']);
        }

        $result = OrderService::sponsorRefund($param);

        return $result ? json(['code' => 1, '退款申请成功!']) : json(['code' => 0, '退款申请失败!']);
    }
}
